import deletePng from '@/assets/images/delete.png';
import edit from '@/assets/images/edit.png';
import plus from '@/assets/images/plus.png';
import { Folder } from '@/types/global';
import { findById } from '@/store/program/utils';
import { nanoid } from 'nanoid';
import { useCloned } from '@vueuse/core';
import { contextmenuConfig } from '../../components/contextmenu/bus';
import { activeId, createFolder, currentFolder, deleteFolder } from '../../bus';

export const onContextmenu = (item: Folder) => {
  const e = window.event as MouseEvent;
  activeId.value = item.id;
  e.preventDefault();
  currentFolder.value = item;
  contextmenuConfig.value = {
    show: true,
    list: [
      {
        title: '重命名',
        action() {
          item.editMode = true;
        },
        icon: edit,
      },
      {
        title: '新建文件夹',
        action() {
          activeId.value = currentFolder.value.id;
          createFolder();
        },
        icon: plus,
      },
      {
        title: '删除',
        action() {
          deleteFolder(item.id);
        },
        icon: deletePng,
      },
    ],
    left: e.x + 10,
    top: e.y,
    target: item,
  };
};
export const drop = (item: Folder) => {
  const e = window.event as DragEvent;
  const ids: Array<string> = JSON.parse(e.dataTransfer?.getData('ids') || '');

  const isSelf = ids.findIndex((v) => {
    if (v === item.id) {
      return v;
    }
    return null;
  });
  if (isSelf < 0) {
    ids.forEach((v) => {
      const target = findById(v);
      if (!target) return;
      if (target.type === 'folder' || !item.children) return;
      const newObject = useCloned(target).cloned.value;
      newObject.id = nanoid();
      item.children.push(newObject);
      currentFolder.value.children = currentFolder.value.children?.filter(
        (m) => {
          return m.id !== v;
        }
      );
    });
  }
};

export const dragEnter = (item: Folder) => {
  item.showChildren = true;
};
